import { Component, OnInit } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { dateFormat, deepClone } from '../../../utils/utils';
import { ApesMessageService} from '@shared/apes/message';
import { GridConfigService } from '@core/config/grid-config.service';
import { GridOptions } from '@ag-grid-community/core';
import { endOfMonth, format, startOfMonth } from 'date-fns';
import { HeaderDayComponent } from '@shared/ag-grid-ext/header-component/header-day.component';
import { HttpClient } from '@angular/common/http';
import {AllModules,Module} from "@ag-grid-enterprise/all-modules";
import { ExportExcelService } from '@core/services/excel/export-excel.service';

@Component({
  selector: 'attendanceMonthly',
  templateUrl: './attendanceMonthly-form.component.html',
  styleUrls: ['./attendanceMonthly-form.component.scss'],
})
export class AttendanceMonthlyFormComponent implements OnInit {
  /** grid 相关 **/
  modules:Module[] =AllModules
  rowData: any[] = [];
  rowDataItem: any[] = [];
  columnDefsMeteData: any[];
  columnDefsItemMeteData: any[];
  columnDefs: any = [];
  gridOptions: GridOptions;
  height: any = 520 + 'px';
  tabList: any = [];
  ctx = { model: {} };
  localeText: any;
  headDate: any;
  /** 按钮相关 **/
  buttonBar = [
    { hide: true, style: 'primary', label: '查询', id: 'action_query', loading: false },
    {hide: true, style: 'default', label: '导出', id: 'action_export'},
    // { hide: true, style: 'default', label: '重置', id: 'action_reset' },
    // { hide: true, style: 'default', label: '展开查询条件', id: 'action_show' },
  ];

  /** 明细数据查询条件 **/
  hind: string = 'none';     // 中间必填项
  timeList: any = [];       // 日期
  startValue: Date = null;
  endValue: Date = null;
  endDate = null;                     // 默认结束时间
  startDate = null;                   // 默认开始时间 当天
  itemsList = {};
  tabsId: string;

  /** 分页器 **/
  total = 0;
  pageSize = 50;
  currentPage = 0;

  /** 获取公司、部门、合作伙伴相关 **/
  hidn: string = 'none';            // 脑袋必填项
  company: any[];
  companyId: string = null;
  dept = [];
  deptId: string = null;
  employee = [];
  employeeId: string = null;
  postId: string = null;
  frameworkComponents;
  checkOne: boolean = false;


  constructor(private apiService: ApiService,
              private msg: ApesMessageService,
              private exportExcelService: ExportExcelService,
              private http: HttpClient,
              private gridConfigService: GridConfigService) {
    this.columnDefsMeteData = [
      { headerName: '公司代码', field: 'COMPANY_ID', width: 100, hide: true, },
      {
        headerName: '公司名称',
        field: 'COMPANY_NAME',
        width: 100,
        pinned: 'left',
      },
      {
        headerName: '部门代码',
        field: 'DEPT_ID',
        width: 100,
        hide: true,
      },
      {
        headerName: '部门名称',
        field: 'DEPT_NAME',
        width: 100,
        pinned: 'left',
      },
      {
        headerName: '岗位代码',
        field: 'POST_ID',
        width: 100,
        hide: true,
      },
      {
        headerName: '岗位名称',
        field: 'POST_NAME',
        width: 100,
        pinned: 'left',
      },
      {
        headerName: '员工代码',
        field: 'EMPLOYEE_ID',
        width: 100,
        hide: true,
      },
      {
        headerName: '法定节假日',
        field: 'HOLIDAYS',
        width: 100,
      },
      {
        headerName: '员工名称',
        field: 'EMPLOYEE_NAME',
        width: 100,
        pinned: 'left',
      },

      {
        headerName: '例休计划',
        field: 'CASE_PLAN',
        width: 100,
      },
      {
        headerName: '法定假加班核算',
        field: 'STATUTORY_OVERTIME',
        width: 140,
      },
      {
        headerName: '例休',
        field: 'CAS',
        width: 70,
      },
      {
        headerName: '加班',
        field: 'OVERTIME',
        width: 70,
      },
      {
        headerName: '应出勤天数',
        field: 'DAYS_TO_ATTEND',
        width: 100,
      },
      {
        headerName: '考勤天数',
        field: 'ATTENDANCE_DAYS',
        width: 100,
      },
      {
        headerName: '考勤天数合计',
        field: 'TOTAL_ATTENDANCE_DAYS',
        width: 120,
      },
      {
        headerName: '工作天数',
        field: 'WORK_DAYS',
        width: 100,
      },
      {
        headerName: '补休',
        field: 'COMPENSATORY_TIME',
        width: 70,
      },
      {
        headerName: '公出/加班晚到/出差/通宵值班补休',
        field: 'GO_OUT',
        width: 100,
      },
      {
        headerName: '工伤',
        field: 'WORK_INJURY',
        width: 70,
      },
      {
        headerName: '病假<=1',
        field: 'SICK_LEAVE',
        width: 90,
      },
      {
        headerName: '病假>1',
        field: 'SICK_LEAVE2',
        width: 90,
      },
      {
        headerName: '年假',
        field: 'ANNUAL_LEAVE',
        width: 70,
      },
      {
        headerName: '产假',
        field: 'MATERNITY_LEAVE',
        width: 70,
      },

      {
        headerName: '婚假',
        field: 'MARRIAGE_LEAVE',
        width: 70,
      },
      {
        headerName: '丧假',
        field: 'FUNERAL_LEAVE',
        width: 70,
      },
      {
        headerName: '陪产假',
        field: 'PATERNITY_LEAVE',
        width: 100,
      },
      {
        headerName: '验错',
        field: 'ERROR_CHECKING',
        width: 70,
      },
      {
        headerName: '入离职不满勤',
        field: 'INCOMING_DISSATISFACTION',
        width: 100,
      },
      {
        headerName: '旷工',
        field: 'COMPLETION',
        width: 70,
      },
      {
        headerName: '事假',
        field: 'LEAVE',
        width: 70,
      },
      {
        headerName: '考勤异常天数',
        field: 'ABNORMAL＿DAYS',
        width: 100,
      },
      {
        headerName: '早退',
        field: 'LEAVE_EARLY',
        width: 70,
      },
      {
        headerName: '迟到',
        field: 'BE_LATE',
        width: 70,
      },
      {
        headerName: '离职人员剩余补休余额',
        field: 'LEAVE_COMPENSATORY_DAY',
        width: 70,
      },
    ];
    this.localeText = gridConfigService.getLocaleText();
  }

  ngOnInit() {

    // 默认 请求 当天 数据
    const today = new Date();
    const startMonth = startOfMonth(today); // Tue Jan 01 2019 00:00:00 GMT+0800 (中国标准时间)
    const startDate = format(startMonth, 'YYYY-MM-DD'); // 2019-01-01 00:
    const endMonth = endOfMonth(today); // Thu Jan 31 2019 23:59:59 GMT+0800 (中国标准时间)
    const endDate = format(endMonth, 'YYYY-MM-DD'); // 2019-01-31 23:59:59
    this.endDate = endDate;
    this.startDate = startDate;
    this.timeList.push(this.startDate);
    this.timeList.push(this.endDate);

    this.frameworkComponents = { headerDay: HeaderDayComponent };
    this.gridOptions = <GridOptions>{
      pagination: true,
      paginationPageSize: 100,
    };
    // this.getCompany();
    // this.getDept();
    // this.getEmployee();
    this.onHead();
    // this.getPartner();
  }

  onRowClick() {

  }

  onHead() {
    this.apiService.post('ding.attendanceMonthlyService.getAttendanceMonthlyHead', { 'TIME_LIST': this.timeList }).subscribe(data => {
      let iLength = data.length;
      this.headDate = data;
      this.columnDefs = deepClone(this.columnDefsMeteData);
      for (let i = 0; i < iLength; i++) {
        this.dynamicField(data[i]);
      }
      // this.columnDefs.push( {
      //   headerName: "例休计划",
      //   field: "REST",
      //   width: 100,
      //   valueGetter: function(params) {
      //     let iCount = 0;
      //     let columnList = params.columnApi.columnController.columnDefs
      //     let iSize = columnList.length-2;
      //     for (let i = 8 ;i< iSize ; i++){
      //       if (params.data[columnList[i].field]==null)
      //         iCount +=1;
      //      }
      //     return iCount;
      //   }
      // });
      // this.columnDefs.push( {
      //   headerName: "应出勤",
      //   field: "ATTENDANCE",
      //   width: 100,
      //   valueGetter: function(params) {
      //     let iCount = 0;
      //     let columnList = params.columnApi.columnController.columnDefs
      //     let iSize = columnList.length-2;
      //     for (let i = 9 ;i< iSize ; i++){
      //       if (params.data[columnList[i].field]!=undefined)
      //         iCount +=1;
      //     }
      //     return iCount;
      //   }
      // });

    });
  }


  onPageIndexChange() {
    this.getTableTabData(this.itemsList);
  }

  dynamicField(item: any) {
    // var name = item.name;
    // var strs = name.split(";"); //字符分割
    let field = {
      headerName: item.name,
      field: item.id,
      width: 60,
      cellRenderer: this.formatDate,
      cellClass: function(params) {
        return params.value === 0 ? 'rubinered' : '';
      },
      headerComponent: 'headerDay',
    };
    this.columnDefs.push(field);
  }

  /**
   * 功能：按钮事件路由
   * @param data 当前按钮元数据
   */
  onEvent(data: any) {
    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.buttonBar[0].loading = true;
        this.action_query();
      }else if (data.id === 'action_export') {
        this.action_export();
      }
      // else if (data.id === 'action_show') {
      //   this.action_show();
      // } else if (data.id === 'action_reset') {
      //         this.action_reset();
      //       }
    }
  }

  /** 主数据 查询按钮事件 **/
  action_query() {
    if (this.timeList.length === 0 && this.companyId === null && this.deptId === null && this.employeeId === null && this.postId === null) {
      this.hidn = 'block';
    } else {
      this.hidn = 'none';
      this.getTableFieldData();
    }
    this.buttonBar[0].loading = false;
  }

  // 导出数据
  action_export() {
    if (this.rowData && this.rowData.length === 0) {
      return;
    }
    const columnList = this.gridOptions.columnDefs;
    this.exportExcelService.exportWithDealData(columnList, this.rowData, '考勤明细统计');
  }

  /** 明细数据 查询按钮事件 **/
  queryBtn() {
    this.getDate(this.timeList, 'startValue', 'endValue');
    // 判断日期不能为空
    if (this.startValue === null) {
      this.hind = 'block';
    } else {
      this.hind = 'none';
    }
    //  必须满足以下条件才能调用接口
    if (this.hind === 'none') {
      this.getTableTabData(this.itemsList);
    }
  }

  /** 点击tab页签触发的事件 **/
  tabChanges(tabId: any) {
    this.currentPage = 0;
    this.tabsId = tabId;
    this.getTableTabData(this.itemsList);
  }


  /** 日期转换 **/
  getDate(time: any[], time_ks: string, time_js: string) {
    // debugger;
    let [first, second] = time;
    if (first) {
      this[time_ks] = first.toISOString().slice(0, 10);
    } else {
      this[time_ks] = null;
    }

    if (second) {
      this[time_js] = second.toISOString().slice(0, 10);
    } else {
      this[time_js] = null;
    }

  }

  /** 主表数据 **/
  getTableFieldData() {
    this.onHead();
    let data = {
      'COMPANY_ID': this.companyId,
      'POST_ID': this.postId,
      'DEPT_ID': this.deptId,
      'EMPLOYEE_ID': this.employeeId,
      'TIME_LIST': this.timeList,
      'checkOne': this.checkOne,
    };
    this.apiService.post('ding.attendanceMonthlyService.loopAttendanceMonthly', { 'body': JSON.stringify(data) }).subscribe(data => {
      if (data) {
        this.rowData = data;
        if (this.rowData.length === 0) {
          this.msg.info(`未找到满足条件的数据`);
        }
      } else {
        this.rowData = [];
        this.msg.info('未找到满足条件的数据');
      }
    });

  }


  /** 明细数据 **/
  getTableTabData(list: any) {
    // this.rowDataItem = [];
    let data = {
      'queryid': 'ledger.items', 'page': this.currentPage, 'size': this.pageSize,
      'LEDGER_ACCOUNT_ID': this.tabsId,
      'ACCOUNTING_DATE_BEGIN': this.startValue, 'ACCOUNTING_DATE_END': this.endValue,
      'COMPANY_ID': list.COMPANY_ID, 'DEPT_ID': list.DEPT_ID, 'PARTNER_ID': list.PARTNER_ID,
      'INVENTORY_MODE': list.INVENTORY_MODE, 'ACCOUNTING_METHOD': list.ACCOUNTING_METHOD,
    };
    this.apiService.post('pub.query', { 'body': JSON.stringify(data) }).subscribe(data => {
      if (data) {
        this.total = data.total;
        this.rowDataItem = data.content;
        if (this.rowDataItem.length === 0) {
          this.msg.info(`未找到满足条件的数据`);
        }
      } else {
        this.msg.info(data.msg);
      }
    });
  }

  /** 获取 公司 **/
  getCompany() {
    let data = { 'pages': 1, 'size': 5000 };
    this.apiService.post('cm.company.find', { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          this.company = body.content;
        } else {
          this.msg.info(body.msg);
        }
      });
  }

  /** 获取 部门 **/
  getDept() {
    let data = { 'size': 10000, page: 0 };
    this.apiService.post('cm.branch.findAll', { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          this.dept = body;
        } else {
          this.msg.info(body.msg);
        }
      });
  }

  /** 获取 员工 **/
  getEmployee() {

    this.apiService.post('hr.employee.findAll', {}).subscribe(
      (body) => {
        if (body) {
          this.employee = body.content;
        } else {
          this.msg.info(body.msg);
        }
      });
  }

  /** 保留两位小数点 **/
  formatDate(params) {
    let key = params.colDef.field;
    let data = params.data[key];
    // if ( data !== undefined ) {
    //   data = 'A';
    // } else{
    //   data = '休';
    // }
    return data;
  }
}

